cmake_minimum_required(VERSION 3.2)

PROJECT(lua51)
INCLUDE(cmake/ModuleImport.cmake)
LIST(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake)
INCLUDE(cmake/ModuleCompileOptions.cmake)
ModuleSetCompileOptions()

SET(LUA51_VERSION_MAJOR "1")
SET(LUA51_VERSION_MINOR "0")
SET(LUA51_VERSION_PATCH "1")
SET(LUA51_VERSION "${LUA51_VERSION_MAJOR}.${LUA51_VERSION_MINOR}.${LUA51_VERSION_PATCH}")

MESSAGE(STATUS "VERSION: ${LUA51_VERSION}")

ADD_DEFINITIONS(-DUSE_LUA51)
ADD_DEFINITIONS(-DLUA_COMPAT_MODULE -DLUA_COMPAT_APIINTCASTS)

IF (WIN32)
    INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}/src/windows)
ENDIF(WIN32)

INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}/)
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}/include)
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}/src)

FILE(GLOB LUA51_SOURCES
${CMAKE_CURRENT_SOURCE_DIR}/include/*.hpp
${CMAKE_CURRENT_SOURCE_DIR}/include/*.h

${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/*.cc
${CMAKE_CURRENT_SOURCE_DIR}/src/*.c
${CMAKE_CURRENT_SOURCE_DIR}/src/*.hpp
${CMAKE_CURRENT_SOURCE_DIR}/src/*.h
)

LIST(FILTER LUA51_SOURCES EXCLUDE REGEX "lua.c$")
LIST(FILTER LUA51_SOURCES EXCLUDE REGEX "luac.c$")
LIST(FILTER LUA51_SOURCES EXCLUDE REGEX "wmain.c$")

FILE(GLOB LUA_SOURCES
${CMAKE_CURRENT_SOURCE_DIR}/src/lua.c
)

IF (WIN32)
    ADD_LIBRARY(lua51 SHARED ${LUA51_SOURCES})
    SET_TARGET_PROPERTIES(lua51 PROPERTIES COMPILE_FLAGS "-DLUA_BUILD_AS_DLL -DLUA_CORE")
    
    ADD_EXECUTABLE(lua ${LUA_SOURCES})
    TARGET_LINK_LIBRARIES(lua lua51)

    SET_TARGET_PROPERTIES(lua51 PROPERTIES COMPILE_FLAGS "-DLUA_BUILD_AS_DLL -DLUA_LIB")
ELSEIF (APPLE)
    ADD_DEFINITIONS(-DLUA_USE_MACOSX)

    ADD_LIBRARY(lua51 SHARED ${LUA51_SOURCES})
    SET_TARGET_PROPERTIES(lua51 PROPERTIES LINK_FLAGS "-Wl,-undefined -Wl,dynamic_lookup")
    ADD_EXECUTABLE(lua ${LUA_SOURCES})
    TARGET_LINK_LIBRARIES(lua lua51 dl)
ELSEIF (UNIX)
    ADD_DEFINITIONS(-DLUA_USE_LINUX)

    ADD_LIBRARY(lua51 SHARED ${LUA51_SOURCES})
    SET_TARGET_PROPERTIES(lua51 PROPERTIES COMPILE_FLAGS "-Wl,-E" )
    ADD_EXECUTABLE(lua ${LUA_SOURCES})
    TARGET_LINK_LIBRARIES(lua lua51 m dl)
ENDIF ()

INSTALL(DIRECTORY include/
    DESTINATION include
    FILES_MATCHING PATTERN "*.h")

    
IF (WIN32)
    INSTALL(TARGETS lua lua51
        RUNTIME DESTINATION bin
        LIBRARY DESTINATION lib
        ARCHIVE DESTINATION lib)
ELSE(WIN32)
    INCLUDE(GNUInstallDirs)
    INSTALL(TARGETS lua lua51
    RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
    LIBRARY DESTINATION /${CMAKE_INSTALL_LIBDIR}
    ARCHIVE DESTINATION /${CMAKE_INSTALL_LIBDIR})
ENDIF(WIN32)

INCLUDE(cmake/cmake_uninstall.cmake)
ADD_UNINSTALL_TARGET()